<?php
/**
 * 一些萌系函数。
 * @author wangtao
 * @version 2011.07.14
 */

/**
 * 添加一个唯一的IP记录
 */
function addIpNotes()
{
	$ip = realIp();
	$db = mysqlDB::con();
	$sql = 'SELECT `nid` FROM `ip_notes` WHERE `ip` = \'' . $ip . '\' LIMIT 0,1';
	$nid = $db->query2one($sql);
	if (empty($nid))
	{
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
		$date = date('Y-m-d H:i:s');
		$sql = 'INSERT INTO `feed`.`ip_notes` (`nid`, `user_agent`, `ip`, `time`)
				VALUES (NULL , \'' . $userAgent . '\', \'' . $ip . '\', \'' . $date . '\');';
		return $db->query($sql);
	}
	return false;
}


/**
 * 根据不同的ID获得不同的表，很搓的分表
 * @param int $pid
 * @return string
 */
function getPostTable($pid)
{
	if ($pid <= 100000) {
		return 'post_into_1';
	}
	elseif ($pid <= 200000) {
		return 'post_into_2';
	}
	elseif ($pid <= 300000) {
		return 'post_into_3';
	}
	elseif ($pid <= 400000) {
		return 'post_into_4';
	}
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function realIp()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

